<template>
  <!--新建工单-->
  <Modal :mask-closable="false" v-model="deviceVisible" width="800" :title="$t('fault.CreateAWorkOrder')"
    class="modal-content-layout">
    <Form ref="deviceForm" :model="formTop" label-position="top" :rules="validateDevice">
      <Row :gutter="16">
        <Col :span="12">
        <!--设备流水号-->
        <FormItem :label="$t('equipCheck.SerialNo')" prop="assetsNo">
          <Select v-model="formTop.deviceMId" filterable clearable :disabled=isFirst2
            :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.SerialNo')}`" :remote-method="handleRemote"
            :loading="searchLoading" @on-select="handleChangeWl">
            <Option v-for="(item, i) in numberList" :value="item.deviceMId" :disabled="item.disabled" :label="item.desc"
              :key="i">
            </Option>
          </Select>
        </FormItem>
        </Col>
        <Col :span="12">
        <!--设备编号-->
        <FormItem :label="$t('equipCheck.EquipmentNo')" prop="deviceNo">
          <Input v-model="formTop.deviceNo" disabled
            :placeholder="`${$t('common.inputInfo')}${$t('equipCheck.EquipmentNo')}`" clearable />

        </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
        <!--设备名称-->
        <FormItem :label="$t('spareParts.EquipmentName')" prop="deviceName">
          <Input v-model="formTop.deviceName" :placeholder="`${$t('common.inputInfo')}${$t('spareParts.EquipmentName')}`"
            clearable disabled />
        </FormItem>
        </Col>
        <Col :span="12">
        <!--故障时间-->
        <FormItem :label="$t('fault.FaultTime')" prop="faultTime">
          <DatePicker :options="optionsdate" v-model="formTop.faultTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
            :placeholder="`${$t('common.selectInfo')}${$t('fault.FaultTime')}`">
          </DatePicker>
        </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :span="12">
        <!--报修时间-->
        <FormItem :label="$t('fault.ApplyDate')" prop="faultTime">
          <DatePicker :options="optionsdate" v-model="formTop.maintainApplyDate" type="datetime" format="yyyy-MM-dd"
            :placeholder="`${$t('common.selectInfo')}${$t('fault.FaultTime')}`">
          </DatePicker>
        </FormItem>
        </Col>
        <Col :span="12">
        <!--报修电话-->
        <FormItem :label="$t('fault.repairPhone')" prop="maintainApplyPhone">
          <Input maxlength="11" :placeholder="`${$t('common.inputInfo')}${$t('fault.PhoneNumber')}`"
            v-model="formTop.maintainApplyPhone" clearable />
        </FormItem>
        </Col>

      </Row>
      <Row :gutter="16">
        <Col :span="12">
        <!--报修人-->
        <FormItem :label="$t('fault.AppliedBy')">
          <Input v-model="formTop.username" clearable disabled />
        </FormItem>
        </Col>
        <Col :span="12">
        <!--维修迫切程度-->
        <FormItem :label="$t('fault.Evergreen')" prop="maintainGrade">
          <Select v-model="formTop.maintainGrade" :placeholder="`${$t('common.selectInfo')}${$t('fault.Evergreen')}`">
            <Option v-for="item in levels" :value="item.value" :label="item.label" :key="item.value">
            </Option>
          </Select>
        </FormItem>
        </Col>

      </Row>
      <Row :gutter="16">
        <Col :span="12">
        <!--是否影响生产-->
        <FormItem :label="$t('fault.ImpactProduction')" prop="affectProductionFlag">
          <!--            <Select v-model="formTop.affectProductionFlag"-->
          <!--                    :placeholder="`${$t('common.selectInfo')}${$t('fault.ImpactProduction')}`">-->
          <!--              <Option v-for="item in effects"-->
          <!--                      :value="item.value"-->
          <!--                      :label="item.label"-->
          <!--                      :key="item.value">-->
          <!--              </Option>-->
          <!--            </Select>-->
          <RadioGroup v-model="formTop.affectProductionFlag">
            <Radio :label="item.value" v-for="item in effects" :key="item.value">
              {{ item.label }}
            </Radio>
          </RadioGroup>
        </FormItem>
        </Col>

      </Row>
      <Row :gutter="16">
        <Col :span="12">
        <!--故障现象-->
        <FormItem :label="$t('fault.Description')">
          <Input type="textarea" :rows="4" :maxlength="200"
            :placeholder="`${$t('common.inputInfo')}${$t('fault.Description')}`" v-model="formTop.faultMessage"
            clearable />
        </FormItem>
        </Col>
        <Col :span="12" :style="{ marginTop: '45px', display: 'flex' }">
        <Upload :show-upload-list="false" accept="image/*" :format="['jpg', 'jpeg', 'png']"
          :before-upload="handleBeforeUpload" type="drag" action="" style="display: inline-block;width:58px;">
          <div style="width: 58px;height:58px;line-height: 58px;">
            <Icon type="ios-camera" size="20"></Icon>
          </div>
        </Upload>
        <div class="demo-upload-list" v-for="(item, index) in uploadList" :key="index">
          <img :src="util.filePathToUrl(item.filePath)">
          <Icon type="ios-close-circle" class="delIcon" @click="deleteImg(index)" />
        </div>
        </Col>
      </Row>
    </Form>
    <div slot="footer">
      <Button type="default" @click="handleCancel">{{ $t('common.Cancle') }}</Button>
      <Button type="primary" :loading="loadingVisible" @click="handleOk">{{ $t('maintenance.Confirmed') }}</Button>
    </div>
  </Modal>
</template>

<script>
import moment from "moment";

export default {
  name: "addModal",
  data() {
    const checkPhone = (rule, value, callback) => {
      let regPone = null;
      let mobile = /^(1[3456789]\d{9})$/;
      let tel = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/;
      if (value !== null && value.charAt(0) === "0") {
        regPone = tel;
      } else if (value !== null && value.charAt(0) !== "0") {
        regPone = mobile;
      }
      if (regPone === null) {
        return callback(new Error("请输入电话"));
      } else if (value && !regPone.test(value)) {
        return callback(new Error("请输入正确的电话格式"));
      } else {
        callback();
      }
    };
    return {
      optionsdate: {
        disabledDate(date) {
          return date && date.getTime() > Date.now();
        },
      },
      deviceVisible: false,
      loadingVisible: false,
      searchLoading: false,
      isFirst: false,
      isFirst2: false,
      formTop: {

      },
      validateDevice: {
        deviceMId: [
          {required: true, message: `${this.$t('common.inputInfo')}${this.$t('equipCheck.SerialNo')}`, trigger: "change"},
        ],
        deviceNo: [
          {required: true, message: `${this.$t('common.inputInfo')}${this.$t('equipCheck.EquipmentNo')}`, trigger: "change"},
        ],
        deviceName: [
          {required: true, message: `${this.$t('common.inputInfo')}${this.$t('spareParts.EquipmentName')}`, trigger: "change"},
        ],
        faultTime: [
          {required: true, type: "date", message: `${this.$t('common.selectInfo')}${this.$t('fault.FaultTime')}`, trigger: "change"},
        ],
        maintainApplyDate: [
          {required: true, type: "date", message: `${this.$t('common.selectInfo')}${this.$t('fault.RenovationTime')}`, trigger: "change"},
        ],
        maintainApplyPhone: [
          {required: false, message: "请输入正确的电话号码",
            // validator: checkPhone,
            pattern: /^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$/,
            trigger: ["blur"],
            transform(value) {
              return value.trim();
            },
          },

        ],
        maintainGrade: [
          {required: true, message: `${this.$t('common.selectInfo')}${this.$t('fault.Evergreen')}`, trigger: "change"},
        ],
        affectProductionFlag: [
          {required: true, message: `${this.$t('common.selectInfo')}${this.$t('fault.ImpactProduction')}`, trigger: "change"},
        ],
      },
      numberList: [],
      numberList2: [],
      levels: [
        {label: "特急", value: '2'},
        {label: "紧急", value: '1'},
        {label: "一般", value: '0'},
      ],
      effects: [
        {label: "影响生产", value: '1'},
        {label: "不影响生产", value: '0'},
      ],
      uploadList: []
    };
  },
  mounted() {

  },
  methods: {
    //文件上传
    handleBeforeUpload(file) {
      let formData = new FormData();
      formData.append("dir", 'device')
      formData.append("file", file)
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.axios({
        method: 'post',
        url: '/fileServer/upload',
        data: formData,
        config,
      }).then(res => {
        if (res.code == 200) {
          this.uploadList.push({
            fileName: res.data.fileName,
            fileUrl: res.data.fileUrl,
            filePath: res.data.filepath,
          })
        }
      })
      return false;
    },
    deleteImg(index) {
      this.uploadList.splice(index, 1)
    },
    show() {
      this.$refs.deviceForm.resetFields();
      this.deviceVisible = true;
      this.formTop = {
        username: localStorage.getItem("ziyunFactoryPortalName"),
        faultTime : moment().format('YYYY-MM-DD HH:mm:ss'),
        maintainApplyDate : moment().format('YYYY-MM-DD')
      }
      this.uploadList = []
      this.numberList = []
      this.numberList2 = []
      this.isFirst = false
      this.isFirst2 = false
    },
    handleRemote(query) {
      if (query !== "") {
        this.searchLoading = true;
        let _query = query.split('-')
        if (Array.isArray(_query)) _query = _query[0]
        this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: _query,
            deviceNo: '',
            assetsNo:"",
            orgCode: ''
          },
        }).then((res) => {
            if (res.code === 200) {
              this.numberList = res.data.map(item=> {
                item.desc = item.deviceMId + '-' + item.deviceName
                return item;
              })
              this.numberList.forEach(val => {
                if (val.deviceStatus === '3') {
                  val.disabled = true
                }
              })
              if (this.isFirst2) {
                this.formTop.deviceMId = query
              }
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.searchLoading = false;
          });
      } else {
        this.numberList = [];
      }
    },
    handleRemote2(query) {
      if (query !== "") {
        this.searchLoading = true;
        this.axios({
          method: "get",
          url: "/dms/dmsDevice/deviceList",
          params: {
            deviceMId: '',
            deviceNo: query,
            orgCode: ''
          },
        })
          .then((res) => {
            if (res.code === 200) {
              this.numberList2 = res.data;
              this.numberList2.forEach(val => {
                if (val.deviceStatus === '3') {
                  val.disabled = true
                }
              })
            } else {
              this.$Message.warning({
                content: res.msg,
                duration: 6,
                closable: true,
              });
            }
          })
          .finally(() => {
            this.searchLoading = false;
          });
      } else {
        this.numberList2 = [];
      }
    },
    handleChangeWl(val) {
      const obj = this.numberList.find(item=> item.deviceMId === val.value)

      if(obj){
        this.formTop.deviceName =  obj.deviceName ||'';
        this.formTop.deviceNo = obj.deviceNo  ||'';
        this.formTop.deviceId = obj.deviceId  ||'';
        this.isFirst = true
      }
    },
    handleChangeWl2(val) {

      if(val){
        let deviceName = this.numberList2.length ? this.numberList2[val.tag].deviceName : '';
        let deviceMId = this.numberList2.length ? this.numberList2[val.tag].deviceMId : '';
        let deviceId = this.numberList2.length ? this.numberList2[val.tag].deviceId : '';
        this.isFirst2 = true
        this.numberList = [this.numberList2[val.tag]]
        this.formTop = {
          ...this.formTop,
          deviceMId,
          deviceName,
          deviceId,
        }
      }
    },
    handleCancel() {
      this.deviceVisible = false;
      this.loadingVisible = false;
    },
    handleOk() {
      let params = {
        deviceMId: this.formTop.deviceMId,
        deviceNo: this.formTop.deviceNo,
        deviceName: this.formTop.deviceName,
        faultTime: this.$moment(this.formTop.faultTime).format("YYYY-MM-DD HH:mm:ss"),
        maintainApplyBy: window.localStorage.getItem("ziyunFactoryUserId"),
        maintainApplyPhone: this.formTop.maintainApplyPhone,
        maintainGrade: this.formTop.maintainGrade,
        affectProductionFlag: this.formTop.affectProductionFlag,
        faultMessage: this.formTop.faultMessage,
        maintainApplyDate:this.$moment(this.formTop.maintainApplyDate).format("YYYY-MM-DD HH:mm:ss"),
        attachmentDTOs: this.uploadList.map(v => ({
          attachmentType: 1,
          ...v
        })),
      };
      this.$refs.deviceForm
        .validate((valid) => {
          if (valid) {
            this.loadingVisible = true;
            this.axios({
              method: "post",
              url: "/dms/workOrder/add",
              data: params,
            }).then((res) => {
              if (res.code === 200) {
                this.deviceVisible = false;
                this.loadingVisible = false;
                this.$Message.success("新增成功！");
                this.$emit("refresh");
              } else {
                this.deviceVisible = false;
                this.loadingVisible = false;
                this.$Message.error(res.msg);
              }
            });
          }
        })
    },
  },
};
</script>

<style lang="scss" scoped>
.demo-upload-list {
  position: relative;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-left: 15px;

  img {
    width: 100%;
    height: 100%;
  }

  .delIcon {
    position: absolute;
    right: -10px;
    top: -10px;
    color: red;
    font-size: 20px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
  }
}
</style>
